package com.halflife.parameter;

import com.halflife.comeElectricity.basic.datadic.DataDic;
import com.halflife.comeElectricity.basic.datadic.DataDicRepository;
import com.halflife.framework.participant.user.UserView;
import com.halflife.framework.utils.ImageUploadUtil;
import com.halflife.parameter.icon.Icon;
import com.halflife.parameter.icon.IconRepository;
import com.halflife.parameter.template.Parameter;
import com.halflife.parameter.template.ParameterRepository;
import com.halflife.parameter.template.Template;
import com.halflife.parameter.template.TemplateRepository;
import com.halflife.shiro.utils.ShiroUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class ParameterSvgController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IconRepository iconRepository;
    @Resource
    private DataDicRepository dataDicRepository;
    @Resource
    private ParameterRepository parameterRepository;
    @Resource
    private TemplateRepository templateRepository;

    @RequestMapping(value = "svg/rider/titleImgeUpload", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> titleImgUpload(HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            MultipartFile file = multipartRequest.getFile("uploadFile");
            String fileName = ImageUploadUtil.upload(request, file);
//            String imageContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String imageContextPath = "";
            //拼接回传地址
            imageContextPath = "/fileUpload/" + sdf.format(new Date()) + "/" + fileName;

            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    @RequestMapping("svg/view")
    public String getIconList(Integer id,String option, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("dataDicTypeId", 14);
        params.put("valid", true);
        List<DataDic> list = dataDicRepository.selectAll(params);
        model.addAttribute("catagorys", list);
        model.addAttribute("templateId", id);
        model.addAttribute("option", option);
        model.addAttribute("option", "view");
        return "svg/project";
    }
    @RequestMapping("svg/operate")
    public String getIconOperates(Integer id,String option, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("dataDicTypeId", 14);
        params.put("valid", true);
        List<DataDic> list = dataDicRepository.selectAll(params);
        model.addAttribute("catagorys", list);
        model.addAttribute("templateId", id);
        model.addAttribute("option", option);

        params.clear();
        params.put("orderSql","t.name");
        params.put("valid", true);
        List<Icon> iconList = iconRepository.selectAll(params);
        Map<String, List<Icon>> icons = new HashMap<>();
        for (DataDic d : list) {
            List<Icon> tempList = new ArrayList<>();
            icons.put(d.getValue(), tempList);
        }
        for (Icon icon : iconList) {
            if (StringUtils.isNotBlank(icon.getPhoto())&&StringUtils.isBlank(icon.getIcon())) {
                icon.setIcon(icon.getPhoto().replaceAll("\\.svg","\\.png").replaceAll("icons\\/","icons_origin\\/"));
            }
            if (icons.containsKey(icon.getCatagory())) {
                icons.get(icon.getCatagory()).add(icon);
            }
//            else {
//                List<Icon> tempList = new ArrayList<>();
//                tempList.add(icon);
//                icons.put(icon.getCatagory(), tempList);
//            }
        }
        model.addAttribute("icons", icons);

//        return "svg/bp_project";
        return "svg/project";
    }
    @RequestMapping("svg/info")
    public String getIconInfos(Integer id,String option, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("dataDicTypeId", 14);
        params.put("valid", true);
        List<DataDic> list = dataDicRepository.selectAll(params);
        model.addAttribute("catagorys", list);
        model.addAttribute("templateId", id);
        model.addAttribute("option", "operate");
        Template template = templateRepository.selectByPrimaryKey(id);
        UserView user = ShiroUtil.getUserView(request);
        if(template!=null){
            Template logTemplate = new Template();
            logTemplate.setId(template.getId());
            logTemplate.setViewCount(template.getViewCount() == null ? 0 : (template.getViewCount() + 1));
            logTemplate.setLastViewerId(user.getId());
            logTemplate.setLastViewerPhoto(user.getProfilePhoto());
            logTemplate.setLastViewerName(user.getName());
            logTemplate.setLastViewTime(new Date());
            templateRepository.updateByPrimaryKeySelective(logTemplate);
        }
        if (template.getUserViewId().intValue() == user.getId().intValue()) {
            model.addAttribute("isMy", 1);
        }else{
            model.addAttribute("isMy", 0);
        }

        params.clear();
        params.put("valid", true);
        List<Icon> iconList = iconRepository.selectAll(params);
        Map<String, List<Icon>> icons = new HashMap<>();
        for (DataDic d : list) {
            List<Icon> tempList = new ArrayList<>();
            icons.put(d.getName(), tempList);
        }
        for (Icon icon : iconList) {
            if (StringUtils.isNotBlank(icon.getPhoto())&&StringUtils.isBlank(icon.getIcon())) {
                icon.setIcon(icon.getPhoto().replaceAll("\\.svg","\\.png").replaceAll("icons\\/","icons_origin\\/"));
            }
            if (icons.containsKey(icon.getCatagory())) {
                icons.get(icon.getCatagory()).add(icon);
            }
//            else {
//                List<Icon> tempList = new ArrayList<>();
//                tempList.add(icon);
//                icons.put(icon.getCatagory(), tempList);
//            }
        }
        model.addAttribute("icons", icons);

//        return "svg/bp_project";
        return "svg/info";
    }
    @RequestMapping("svg/operate/parameter/{id}")
    public String getParameter(@PathVariable() Integer id,Integer iconId, Integer parameterId,String iconName,String memo,HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("valid", true);
        params.put("dataDicTypeId", 9);
        List<DataDic>  lensList = dataDicRepository.selectAll(params);
        model.addAttribute("lensList", lensList);
        params.put("dataDicTypeId", 10);
        List<DataDic>  isoList = dataDicRepository.selectAll(params);
        model.addAttribute("isoList", isoList);
        params.put("dataDicTypeId", 11);
        List<DataDic>  apertureList = dataDicRepository.selectAll(params);
        model.addAttribute("apertureList", apertureList);
        params.put("dataDicTypeId", 12);
        List<DataDic>  shutterList = dataDicRepository.selectAll(params);
        model.addAttribute("shutterList", shutterList);
        params.put("dataDicTypeId", 13);
        List<DataDic>  cameraHoldingList = dataDicRepository.selectAll(params);
        model.addAttribute("cameraHoldingList", cameraHoldingList);
        String url = "view/parameter";


        Parameter parameter;
        if(parameterId!=null){
            parameter = parameterRepository.selectByPrimaryKey(parameterId);
        }else{
            parameter = new Parameter();
            parameter.setIconId(iconId);
            parameter.setTemplateId(id);
        }
        if (iconId != null) {
            Icon icon = iconRepository.selectByPrimaryKey(iconId);
            model.addAttribute("icon", icon);
        } else {

            parameter.setHeight(memo);
            url = "view/line";
        }
        model.addAttribute("parameter", parameter);

        return url;
    }
    @PostMapping("svg/operate/parameter/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(Parameter parameter, HttpServletRequest request,
                               HttpServletResponse response, Model model) {
        try {

            if(parameter.getId()!=null){
                parameterRepository.updateByPrimaryKeySelective(parameter);
            }else {
                parameter.init();
                parameter.setValid(false);
                parameterRepository.insert(parameter);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(0, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(parameter.getId(), HttpStatus.OK);
    }
}
